<template>
  <div class="advanced-search">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索笔记..."
        clearable
        @input="handleSearch"
        @focus="showHistory = true"
        @blur="handleBlur"
        :size="isMobile ? 'default' : 'large'"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
        <template #suffix>
          <el-button 
            type="text" 
            @click="toggleAdvanced"
            :icon="isAdvanced ? ArrowUp : ArrowDown"
          />
        </template>
      </el-input>
      
      <!-- 搜索历史 -->
      <SearchHistory
        v-if="showHistory && searchQuery === ''"
        v-model="searchQuery"
        @search="handleHistorySearch"
      />
    </div>

    <!-- 高级搜索选项 -->
    <div v-if="isAdvanced" class="advanced-options">
      <div class="filter-section">
        <h4>标签筛选</h4>
        <div class="tag-filters">
          <el-tag
            v-for="tag in availableTags"
            :key="tag"
            :type="selectedTags.includes(tag) ? 'primary' : 'info'"
            @click="toggleTag(tag)"
            style="cursor: pointer; margin: 4px;"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>

      <div class="filter-section">
        <h4>分类筛选</h4>
        <el-select
          v-model="selectedCategory"
          placeholder="选择分类"
          clearable
          style="width: 100%;"
        >
          <el-option
            v-for="category in availableCategories"
            :key="category"
            :label="category"
            :value="category"
          />
        </el-select>
      </div>

      <div class="filter-section">
        <h4>其他选项</h4>
        <div class="other-filters">
          <el-checkbox v-model="favoriteOnly">
            只显示收藏笔记
          </el-checkbox>
        </div>
      </div>

      <div class="filter-section">
        <h4>排序</h4>
        <div class="sort-options">
          <el-select v-model="sortBy" style="width: 120px;">
            <el-option label="更新时间" value="updatedAt" />
            <el-option label="创建时间" value="createdAt" />
            <el-option label="标题" value="title" />
          </el-select>
          <el-button-group>
            <el-button 
              :type="sortOrder === 'desc' ? 'primary' : 'default'"
              @click="sortOrder = 'desc'"
            >
              降序
            </el-button>
            <el-button 
              :type="sortOrder === 'asc' ? 'primary' : 'default'"
              @click="sortOrder = 'asc'"
            >
              升序
            </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="filter-actions">
        <el-button @click="clearFilters" size="small">
          清除筛选
        </el-button>
        <el-button @click="applyFilters" type="primary" size="small">
          应用筛选
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Search, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import SearchHistory from './SearchHistory.vue'
import { useNotesStore } from '@/stores/notes'

interface Props {
  modelValue?: string
}

interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'search', value: string): void
  (e: 'filters-change', filters: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const notesStore = useNotesStore()

// 响应式检测
const isMobile = computed(() => {
  return window.innerWidth < 768
})

// 搜索状态
const searchQuery = ref(props.modelValue || '')
const showHistory = ref(false)
const isAdvanced = ref(false)

// 筛选选项
const selectedTags = ref<string[]>([])
const selectedCategory = ref('')
const favoriteOnly = ref(false)
const sortBy = ref<'createdAt' | 'updatedAt' | 'title'>('updatedAt')
const sortOrder = ref<'asc' | 'desc'>('desc')

// 可用选项
const availableTags = computed(() => notesStore.tags)
const availableCategories = computed(() => notesStore.categories)

// 监听搜索查询变化
watch(searchQuery, (newValue) => {
  emit('update:modelValue', newValue)
})

// 处理搜索
const handleSearch = () => {
  emit('search', searchQuery.value)
  if (searchQuery.value.trim()) {
    notesStore.searchNotes(searchQuery.value)
  }
}

// 处理搜索历史选择
const handleHistorySearch = (query: string) => {
  searchQuery.value = query
  showHistory.value = false
  handleSearch()
}

// 处理失焦
const handleBlur = () => {
  setTimeout(() => {
    showHistory.value = false
  }, 200)
}

// 切换高级搜索
const toggleAdvanced = () => {
  isAdvanced.value = !isAdvanced.value
}

// 切换标签选择
const toggleTag = (tag: string) => {
  const index = selectedTags.value.indexOf(tag)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value = [...selectedTags.value, tag]
  }
}

// 应用筛选
const applyFilters = () => {
  const filters = {
    query: searchQuery.value,
    tags: selectedTags.value,
    category: selectedCategory.value,
    favoriteOnly: favoriteOnly.value,
    sortBy: sortBy.value,
    sortOrder: sortOrder.value
  }
  
  notesStore.setFilters(filters)
  emit('filters-change', filters)
}

// 清除筛选
const clearFilters = () => {
  searchQuery.value = ''
  selectedTags.value = []
  selectedCategory.value = ''
  favoriteOnly.value = false
  sortBy.value = 'updatedAt'
  sortOrder.value = 'desc'
  
  notesStore.clearSearch()
  emit('filters-change', {})
}

// 暴露方法
defineExpose({
  clearFilters,
  applyFilters
})
</script>

<style scoped>
.advanced-search {
  position: relative;
}

.search-bar {
  position: relative;
}

.advanced-options {
  margin-top: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.filter-section {
  margin-bottom: 16px;
}

.filter-section:last-child {
  margin-bottom: 0;
}

.filter-section h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.tag-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.sort-options {
  display: flex;
  gap: 8px;
  align-items: center;
}

.filter-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .advanced-options {
    padding: 12px;
  }
  
  .sort-options {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-actions {
    flex-direction: column;
  }
  
  .filter-actions .el-button {
    width: 100%;
  }
}
</style> 